import {
    Button,
    HStack,
    Input,
    InputGroup,
    InputLeftElement,
    InputRightElement,
    Stack,
    Text,
    useColorModeValue,
    VStack,
    Popover,
    PopoverTrigger,
    PopoverContent,
    PopoverHeader,
    PopoverBody,
    PopoverFooter,
    PopoverArrow,
    PopoverCloseButton,
    PopoverAnchor,
    Portal,
    Toast,
    useToast,
    ButtonGroup,
    useDisclosure,
    Box,
    FormLabel,
    InputRightAddon,
    InputLeftAddon,
    Textarea, Flex,
} from '@chakra-ui/react'
import {
    ArrowForwardIcon, ArrowLeftIcon, ArrowRightIcon,
    CalendarIcon,
    CheckIcon,
    DeleteIcon,
    EditIcon,
    EmailIcon,
    PhoneIcon,
    SearchIcon
} from "@chakra-ui/icons";
import ManageSearchBar from "../../../components/ManageSearchBar.jsx";
import React, {useEffect, useState} from "react";
import {useAuth} from "../../../hooks/index.js";
import {useNavigate} from "react-router-dom";

import {
    Drawer,
    DrawerBody,
    DrawerFooter,
    DrawerHeader,
    DrawerOverlay,
    DrawerContent,
    DrawerCloseButton,
} from '@chakra-ui/react'
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import {handleResult, handleResultNoRoute} from "../../../api/result.js";
import {delOrder, findByName, getAllOrder, getAllOrderPage, getOrderCount, saveOrder} from "../../../api/order.js";

dayjs.extend(customParseFormat);
const dateFormat = 'YYYY-MM-DD';

export function OrderManagePage() {
    const navigator = useNavigate()
    const toast = useToast()
    const {authInfo} = useAuth()

    // 数据获取
    const [orders, setOrders] = useState([])
    const [total, setTotal] = useState(0) // 总条数
    useEffect(() => {
        console.log(authInfo)
        // 请求数据
        getAllOrderPage({page: 0, size: 6}).then((res) => {
            console.log(res)
            setOrders(res.data)
        })
        getOrderCount().then(r => {
            setTotal(parseInt(r.data))
            console.log(total)
        })
    }, []);

    // ManageSearchBar states
    const [value, setValue] = useState('')
    let timer = new Date()
    const [startDate, setStartDate] = useState(timer.toLocaleDateString())
    const [endDate, setEndDate] = useState(timer.toLocaleDateString())

    let searchItem = {
        placeholder: '学生或医生名称',
        value,
        onChange: (e) => {
            setValue(e.target.value)
        },
        onClick: (e) => {
            if (value === '') {
                getAllOrder().then(r => {
                    console.log(r.data)
                    handleResultNoRoute(r, toast, '', '查询成功')
                    setOrders(r.data)
                })
                return
            }
            findByName(value).then(r => {
                console.log(r.data)
                handleResultNoRoute(r, toast, '', '查询成功')
                setOrders(r.data)
            })
        }
    }
    let dateSearchItem = {
        onChange: (date, dateString) => {
            console.log(date, dateString)
            setStartDate(dateString[0])
            setEndDate(dateString[1])
        },
        onClick: (e) => {
            console.log(startDate, endDate)
        }
    }
    // 当前页码
    const [curIdx, setCurIdx] = useState(0);
    let pageSearchItem = {
        total: (Math.floor(total / 6) + 1), curIdx,
        onChange: (e) => {
            setCurIdx(e.target.value)
        },
        onLeftClick: () => {
            console.log(curIdx)
            if (curIdx > 1) {
                setCurIdx((curIdx - 1))
                return
            }
            toast({
                title: `已到达第一页!`,
                status: 'warning',
                position: 'top',
                isClosable: true,
            })
        },
        onRightClick: () => {
            if (curIdx < (Math.floor(total / 6) + 1)) {
                setCurIdx((curIdx + 1))
                return
            }
            toast({
                title: `已到达最后一页!`,
                status: 'warning',
                position: 'top',
                isClosable: true,
            })
        },
        onClick: () => {
            console.log(curIdx)
            getAllOrderPage({page: curIdx, size: 6})
                .then(r => {
                    handleResultNoRoute(r, toast, '', '查询成功')
                    setOrders(r.data)
                })
        }
    }

    // 添加按钮 弹出drawer
    const {isOpen, onOpen, onClose} = useDisclosure()
    // 用于弹出时聚焦
    const firstField = React.useRef()

    function onAddClick() {
        onOpen()
    }

    // drawer里的表单的数据
    const [doctorId, setDoctorId] = useState('')
    const [studentId, setStudentId] = useState('')

    // 操作栏
    function handleDelClick(id) {
        delOrder(id).then(r => {
            handleResult(r, toast, '', '删除成功')
        })
    }

    function handleUptClick(id) {
        navigator(`/order/${parseInt(id)}`)
    }

    return (
        <>
            <Stack
                mb={6}
                className={useColorModeValue('', 'dark')}
                align={'start'}
                justify={'start'}
                spacing={4}
            >
                <ManageSearchBar
                    pageSearchItem={pageSearchItem}
                    onAddClick={onAddClick}
                    searchItem={searchItem}
                    dateSearchItem={dateSearchItem}/>
                <div className={"table-container " + useColorModeValue('', 'dark')}>
                    <table className="table table-hover">
                        <thead>
                        <tr>
                            <th>医生名称</th>
                            <th>学生名称</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {
                            // doctors.map((item,i)=>{
                            orders.map((item) => (
                                <tr key={item.id}>
                                    <td>{item.doctor.name}</td>
                                    <td>{item.student.name}</td>
                                    <td>{item.createTime}</td>
                                    <td>
                                        <Stack direction='row' spacing={4}>
                                            <Button
                                                onClick={handleUptClick.bind(this, item.id)}
                                                leftIcon={<EditIcon/>} size='sm'
                                                colorScheme='teal' variant='solid'>
                                                编辑
                                            </Button>
                                            <Popover
                                                placement='right'
                                                closeOnBlur={false}
                                            >
                                                <PopoverTrigger>
                                                    <Button
                                                        leftIcon={<DeleteIcon/>} size='sm'
                                                        colorScheme='red' variant='solid'>
                                                        删除
                                                    </Button>
                                                </PopoverTrigger>
                                                <PopoverContent>
                                                    <PopoverHeader fontWeight='semibold'>
                                                        Confirmation
                                                    </PopoverHeader>
                                                    <PopoverArrow/>
                                                    <PopoverCloseButton/>
                                                    <PopoverBody>
                                                        你确定要删除该条数据吗?
                                                    </PopoverBody>
                                                    <PopoverFooter display='flex' justifyContent='flex-end'>
                                                        <ButtonGroup size='sm'>
                                                            <Button
                                                                onClick={() => handleDelClick(item.id)}
                                                                colorScheme='red'>确认</Button>
                                                        </ButtonGroup>
                                                    </PopoverFooter>
                                                </PopoverContent>
                                            </Popover>
                                        </Stack>
                                    </td>
                                </tr>
                            ))
                        }
                        </tbody>
                    </table>
                    <Drawer
                        size={'md'}
                        isOpen={isOpen}
                        placement='right'
                        initialFocusRef={firstField}
                        onClose={onClose}
                    >
                        <DrawerOverlay/>
                        <DrawerContent>
                            <DrawerCloseButton/>
                            <DrawerHeader borderBottomWidth='1px'>
                                创建医生信息
                            </DrawerHeader>

                            <DrawerBody>
                                <Stack spacing='24px'>
                                    <Box>
                                        <FormLabel htmlFor='studentId'>学生学号</FormLabel>
                                        <Input
                                            ref={firstField}
                                            id='studentId'
                                            value={studentId}
                                            onChange={(e) =>
                                                setStudentId(e.target.value)}
                                            placeholder='输入学生学号'
                                        />
                                    </Box>
                                </Stack>
                                <Stack spacing='24px'>
                                    <Box>
                                        <FormLabel htmlFor='doctorId'>医生编号</FormLabel>
                                        <Input
                                            id='doctorId'
                                            value={doctorId}
                                            onChange={(e) =>
                                                setDoctorId(e.target.value)}
                                            placeholder='输入医生编号'
                                        />
                                    </Box>
                                </Stack>
                            </DrawerBody>

                            <DrawerFooter borderTopWidth='1px'>
                                <Button variant='outline' mr={3} onClick={onClose}>
                                    取消
                                </Button>
                                <Button onClick={() => {
                                    saveOrder({doctorId, studentId}).then(r =>
                                        handleResult(r, toast, null, '添加成功')
                                    )
                                }} colorScheme='blue'>提交</Button>
                            </DrawerFooter>
                        </DrawerContent>
                    </Drawer>
                </div>
            </Stack>
        </>
    )
}